package com.cgw.game.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * @Description SurfaceView应用
 * @Author YF
 * @Date 2020/8/12
 * @Version 1.0
 */
class MySurfaceView extends SurfaceView implements Runnable, SurfaceHolder.Callback {
    private SurfaceHolder mHolder; // 用于控制SurfaceView
    private Thread t; // 绘制线程
    private boolean flag; // 线程运行的标识，用于控制线程
    private Canvas mCanvas; // 画布
    private Paint mPaint; // 画笔
    private int width;
    private int height;

    public MySurfaceView(Context context) {
        this(context,null);
    }

    public MySurfaceView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MySurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mHolder = getHolder(); // 获得SurfaceHolder对象
        mHolder.addCallback(this); // 为SurfaceView添加状态监听
        mPaint = new Paint(); // 创建一个画笔对象
        mPaint.setAntiAlias(true);
        setFocusable(true); // 设置焦点
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        t = new Thread(this); // 创建一个线程对象
        flag = true; // 把线程运行的标识设置成true
        t.start(); // 启动线程
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void run() {
       while (flag){
           //绘制方法
           draw();
           try {
               Thread.sleep(100); // 让线程休息50毫秒
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
    }

    private void draw() {
        mCanvas = mHolder.lockCanvas(); // 获得画布对象，开始对画布画画
        mPaint.setColor(Color.RED);
        mCanvas.drawRGB(255, 255, 255); // 把画布填充为黑色
        mCanvas.drawCircle(width/2, height/2, 100, mPaint); // 画一个圆
        mHolder.unlockCanvasAndPost(mCanvas); // 完成画画，把画布显示在屏幕上
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        width = measureSize(widthMeasureSpec);
        height = measureSize(heightMeasureSpec);
        setMeasuredDimension(width,height);
    }
    private int measureSize(int measureSpec) {
        int length;
        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);
        if(mode == MeasureSpec.EXACTLY){
            length = size;
        }else{
            length = DensityUtil.dip2px(getContext(),100);
            if(mode == MeasureSpec.AT_MOST){
                length = Math.min(length,size);
            }
        }
        return length;
    }
}
